<!-- CommentSectionX.vue 评论子系统 -->
<template>
  <div class="comment-system">
    <!-- 评论表单 -->
    <CommentForm
        :currentReplyId="currentReplyId"
        @submit="handleSubmit"
        @cancel="cancelReply"
    />

    <!-- 评论列表 -->
    <CommentList
        :comments="comments"
        @reply="handleReply"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import request from '@/utils/request'
import CommentForm from './CommentForm.vue'
import CommentList from './CommentList.vue'
import {ElMessage} from "element-plus";

const props = defineProps(['writtenId'])
const emit = defineEmits(['comment-submitted'])

// 数据管理
const comments = ref([])
const currentReplyId = ref(null)

// 加载评论
const loadComments = async () => {
  request.get(`/comment/selectByWrittenId/${props.writtenId}`).then (res => {
    if (res.code === 200) {
      comments.value = buildTree(res.data)
    }else{
      ElMessage.error(res.msg)
    }
  })
}

// 构建树形结构
const buildTree = (items) => {
  const map = {}
  return items.filter(item => {
    map[item.id] = { ...item, children: [] }
    if (item.parentId && map[item.parentId]) {
      map[item.parentId].children.push(map[item.id])
      return false
    }
    return true
  })
}

// 处理回复
const handleReply = (commentId) => {
  currentReplyId.value = commentId
}

// 提交评论
const handleSubmit = async (content) => {
  await request.post('/comment/createComment', {
    writtenId: props.writtenId,
    content,
    parentId: currentReplyId.value
  })
  await loadComments()
  emit('comment-submitted') // 通知父组件
}

const cancelReply = () => {
  currentReplyId.value = null
}

onMounted(loadComments)
</script>